<template>
  <div class="question-Box">
    <el-row :gutter="20" type="flex">
      <el-col :span="8" class="question-scoll">
        <NewCard title="学习科目" :border="false">
            <el-table
                :data="subData"
                highlight-current-row
                @row-click="rowClick"
                style="width: 100%"
                v-hasPermi="['assess:exam:edit']">
                <el-table-column
                    :show-overflow-tooltip="true"
                    prop="name"
                    label="科目">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.name" placeholder="科目" class="tableInput" @blur="blurTableInput(scope.row)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="questionNum"
                    label="题数"
                    width="50">
                </el-table-column>
                <el-table-column
                    prop="pass"
                    label="及格率"
                    width="60">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.pass" placeholder="及格率" class="tableInput" @blur="blurTableInput(scope.row)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="price"
                    label="定价"
                    width="50">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.price" placeholder="定价" class="tableInput" @blur="blurTableInput(scope.row)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="giveVoucher"
                    label="奖励问金"
                    width="80">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.giveVoucher" placeholder="奖励问金" class="tableInput" @blur="blurTableInput(scope.row)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="minutes"
                    label="关闭时长(min)"
                    width="100">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.minutes" placeholder="关闭时长" class="tableInput" @blur="blurTableInput(scope.row)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                    label="状态"
                    align="right">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.status" active-color="#f87a23" active-value="1" inactive-value="0" @change="blurTableInput(scope.row)"></el-switch>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <div class="pagination">
                <el-pagination
                    @current-change="handleCurrentChange"
                    :page-sizes="[10, 20, 30, 40]"
                    :pager-count="5"
                    layout="total, prev, pager, next"
                    :total="pageing.total">
                </el-pagination>
            </div>

            <!-- 添加按钮 -->
            <div class="addBox" v-hasPermi="['assess:exam:add']">
                <el-button type="primary" v-if="addBtnShow" @click="clickAddBtn">+ 添加科目</el-button>
                <div class="addForm" v-else>
                    <div class="addForm-input">
                        <el-input v-model="addFrom.name" size="mini" placeholder="科目"></el-input>
                        <!-- <el-input v-model="addFrom.topicNum" placeholder="题数"></el-input> -->
                        <el-input v-model="addFrom.pass" size="mini" placeholder="及格率"></el-input>
                        <el-input v-model="addFrom.price" size="mini" placeholder="定价"></el-input>
                        <el-input v-model="addFrom.giveVoucher" size="mini" placeholder="奖励问金"></el-input>
                        <el-input v-model="addFrom.minutes" size="mini" placeholder="关闭时长(min)"></el-input>
                    </div>
                    <div class="addForm-btn">
                        <el-button type="primary" class="addBtn" round @click="addSubBtn">确认</el-button>
                        <el-button round @click="clickCancel">取消</el-button>
                    </div>
                </div>
            </div>
        </NewCard>
      </el-col>
      <el-col :span="16" class="question-scoll">
        <NewCard :title="selectExam.name?selectExam.name:'请选择学习科目'" :border="false" :isright="true">
            <template slot="right">
                <el-button type="text" class="handleBtn" @click="openCondition" v-if="selectExam.id">学习情况</el-button>
            </template>

            <div class="quesScoll-box" ref="quesScollBox">
                <el-collapse v-model="activeName" v-if="questionList.length" ref="collapse">
                    <el-collapse-item :name="index" v-for="(item,index) in questionList" :key="index">
                        <template slot="title">
                            <div class="coll-title" @click.stop="stopProp">
                                <i class="el-icon-remove" @click.stop="removeQlist(index)"></i>
                                <!-- <p>{{item.question}}</p> -->
                                <el-input v-model="item.question" placeholder="请输入..." maxlength="200" @focus="titleFocus" @blur="titleBlur"></el-input>
                            </div>
                        </template>
                        <!-- 答案列表 -->
                        <ul>
                            <li v-for="(opt,key,optIndex) in item.options" :key="key">
                                <i class="el-icon-remove" @click="removeAlist(item,item.options,key)"></i>
                                <!-- <p>{{opt}}-{{key}}-{{index}}</p> -->
                                <el-input placeholder="请输入..." v-model="item.options[optIndex+1]"></el-input>
                                <el-checkbox v-model="item.answerArray" :label="key" @change="checkAnswer(item)">选为答案</el-checkbox>
                            </li>
                        </ul>
                        <!-- 添加一条答案 -->
                        <svg-icon icon-class="add-icon" class="addAnswer" @click="addAlist(item)"/>
                        <!-- 题目提示 -->
                        <div class="inputTxt">
                            <p>题目提示</p>
                            <WangEditor :wangkey="index+1" ref="wangEditor" :list="item.tipArr" :uploadimg="uploadimg" :isStudy="isStudy"></WangEditor>
                        </div>
                        <div class="inputTxt">
                            <p>答案解析</p>
                            <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="item.analysis"></el-input>
                        </div>
                    </el-collapse-item>
                    <!-- <el-collapse-item name="1">
                        <template slot="title">
                            <div class="coll-title">
                                <i class="el-icon-remove"></i>
                                <p>以下哪些服务态度，是平台严令禁止，如检测到会被予以最高200元罚款的？</p>
                            </div>
                        </template>
                        <ul>
                            <li>
                                <i class="el-icon-remove"></i>
                                <el-input placeholder="请输入..."></el-input>
                                <el-radio v-model="selectRadio" label="1">选为答案</el-radio>
                            </li>
                            <li>
                                <i class="el-icon-remove"></i>
                                <el-input placeholder="请输入..."></el-input>
                                <el-radio v-model="selectRadio" label="2">选为答案</el-radio>
                            </li>
                            <li>
                                <i class="el-icon-remove"></i>
                                <el-input placeholder="请输入..."></el-input>
                                <el-radio v-model="selectRadio" label="3">选为答案</el-radio>
                            </li>
                        </ul>
                        <svg-icon icon-class="add-icon" class="addAnswer"/>
                        <div class="inputTxt">
                            <p>题目提示</p>
                            <WangEditor :wangkey="2" ref="wangEditor1" :list="detailContent1"></WangEditor>
                        </div>
                        <div class="inputTxt">
                            <p>答案解析</p>
                            <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="textarea2"></el-input>
                        </div>
                    </el-collapse-item> -->
                </el-collapse>

                <!-- 空状态 -->
                <div class="analysis-empty" v-else>
                    <img src="~@/assets/images/wjg_img@2x.png" alt="">
                    <p>暂无内容</p>
                </div>
            </div>

            <!-- 按钮区 -->
            <SubBtn v-if="selectExam.id">
                <template slot="btn">
                    <el-button round @click="addQuestion">添加题目</el-button>
                    <el-button type="primary" round class="addBtn" v-hasPermi="['assess:question:add']" @click="clickSave">保存</el-button>
                </template>
            </SubBtn>

            <!-- 学习情况抽屉 -->
            <el-drawer
                title="学习情况"
                size="65%"
                :visible.sync="showDrawer">
                <situation :selectExam="selectExam"></situation>
            </el-drawer>
        </NewCard>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import NewCard from "@/wss/components/newCard.vue";
import SubBtn from "@/wss/components/subBtn.vue";
import WangEditor from "@/wss/components/wangEditor.vue";

import situation from "./situation.vue"
import {getExamListApi,addAssessExamApi,editAssessExamApi} from "@/wss/newApi_3-24/assess/exam.js"
// 题目
import {getQuestionListApi,addQuestionListApi} from "@/wss/newApi_3-24/assess/question.js"
//防抖：debounce 用户触发事件过于频繁，只要最后一次事件的操作
import debounce from "lodash/debounce";
export default {
    name: 'question',
    components: {NewCard,SubBtn,WangEditor,situation},
    data(){
        return{
            // 分页
            pageing: { pageNum: 1, pageSize: 10, total: 0 },
            subData: [],// 学习科目

            addBtnShow: true,//添加按钮显示隐藏
            // 添加科目
            addFrom:{
                name: '',//名称
                pass: '',//及格率
                price: '',//定价
                giveVoucher: '',//奖励问金
                minutes: '',//关闭时长
            },
            selectExam: {},//选择一个科目

            // ------------------------右边题目------------------------
            questionList:[],//题目列表
            activeName: ['0'],
            selectRadio: '1',//选为答案
            textarea1:'',
            textarea2:'',

            detailContent: [],//富文本
            detailContent1: [],//富文本1
            uploadimg:'/doc/overall/upload/studyTips',//上传图片的接口
            isStudy: true,//富文本当前是学习模块

            // 学习情况抽屉
            showDrawer: false,//抽屉隐藏显示
        }
    },
    mounted(){
        this.getExamList() // 查询所有科目
    },
    methods:{
        // 查询所有科目
        async getExamList(){
            let result = await getExamListApi(this.pageing)
            if(result.code == 200){
                this.subData = result.rows
                this.pageing.total = result.total
            }
        },

        // 添加一条科目
        async addAssessExam(){
            let data = {
                name: this.addFrom.name,//名称
                pass: this.addFrom.pass,//及格率
                price: this.addFrom.price,//定价
                giveVoucher: this.addFrom.giveVoucher,//奖励问金
                minutes: this.addFrom.minutes,//关闭时长
            }
            let result = await addAssessExamApi(data)
            if(result.code == 200){
                this.$message({type:'success',message:'添加成功'})
                this.addBtnShow = true
                this.addFrom = {
                    name: '',//名称
                    pass: '',//及格率
                    price: '',//定价
                    giveVoucher: '',//奖励问金
                    minutes: '',//关闭时长
                }
            }
        },

        // 分页器回调 点击下一页
        handleCurrentChange(val) {
            this.pageing.pageNum = val //当前页
            this.getExamList() //发请求
        },

        // 点击表格某一条的回调
        rowClick(row){
            if(this.selectExam.id == row.id) return //不要重复发请求
            this.selectExam = row
            this.getQuestionList() // 根据科目获取题目
        },

        // 修改表格失去焦点的时候
        blurTableInput(row){
            console.log(row);
            if(row.name==='' || row.pass==='' || row.price==='' || row.giveVoucher==='' || row.minutes===''){
                this.$message({type:'warning',message:'请填写完整'})
                return
            }
            this.editAssessExam(row)  // 修改科目的接口
        },

        // 修改科目的接口
        async editAssessExam(data){
            let result = await editAssessExamApi(data)
            if(result.code == 200){
                this.$message({type:'success',message:'编辑成功'})
            }
        },

        // ------------------按钮区------------------
        // 点击添加角色
        clickAddBtn(){
            this.addBtnShow = false
        },

        // 点击添加按钮 添加一条科目
        async addSubBtn(){
            if(this.addFrom.name=='' || this.addFrom.pass=='' || this.addFrom.price=='' || this.addFrom.giveVoucher=='' || this.addFrom.minutes==''){
                this.$message({type:'warning',message:'请填写完整'})
                return
            }
            for (let i = 0; i < this.subData.length; i++) {
                if(this.subData[i].name == this.addFrom.name){
                    this.$message({type:'error',message:'科目名称请勿相同'})
                    return
                }
            }
            await this.addAssessExam()// 添加一条科目
            this.getExamList() // 重新查询所有科目
        },

        // 点击取消按钮
        clickCancel(){
            this.addBtnShow = true
            this.addFrom = {
                name: '',//名称
                pass: '',//及格率
                price: '',//定价
                giveVoucher: '',//奖励问金
                minutes: '',//关闭时长
            }
        },

        // --------------------------------------题目列表--------------------------------------
        //阻止折叠面板冒泡事件
        stopProp(){
            e.stopPropagation()
        },

        // 输入框输入时，将折叠面板的折叠方法设置为空
        titleFocus() {
            this.collClick = this.$refs.collapse.setActiveNames
            this.$refs.collapse.setActiveNames = () => {}
        },
        
        // 输入框失焦时，将折叠面板的方法恢复
        titleBlur() {
            this.$refs.collapse.setActiveNames = this.collClick
        },

        // 根据科目获取题目
        async getQuestionList(){
            let params = {
                create_by: this.selectExam.createBy,
                examId: this.selectExam.id,
            }
            let result = await getQuestionListApi(params)
            if(result.code == 200){
                let qArr = JSON.parse(JSON.stringify(result.rows))
                qArr.forEach(item => {
                    item.tipArr = [item.tips ?? ""]; // 富文本需要的数组
                    item.answerArray = item.answerStringArray.split(",")// 显示设为的答案 数组
                });
                this.questionList = JSON.parse(JSON.stringify(qArr))
            }
        },

        // 点击添加一个题目
        addQuestion: debounce(function(){
            let data = {
                analysis: '',//答案解析
                answerArray: [],//答案的数组
                answerStringArray: '',//答案的字符串，例如1,2,4
                examId: this.selectExam.id,//科目id
                options: {},//选项
                question: '',//问题
                status: '',//状态 1已发布 0未发布
                tips: '',//提示
                tipArr: [],// 富文本需要的数组
            }
            this.questionList.push(data) //添加
            // 滚动到最下面
            this.$nextTick(() => {
                let quesScollBox = this.$refs.quesScollBox
                quesScollBox.scrollTop = quesScollBox.scrollHeight;
            })
        },500),

        // 更改 选为答案 的时候
        checkAnswer(item){
            item.answerStringArray = item.answerArray.join(',')
        },

        // 删除一个题目
        removeQlist(index){
            // 根据下标去删数据
            this.questionList.splice(index,1)
        },

        // 删除一个答案
        removeAlist(item,options,key){
            // 先把答案存下来
            let answerArr = []
            item.answerArray.forEach(item=>{
                answerArr.push(options[item])
            })

            // 更新下标--------------
            // options是对象
            this.$delete(options,key)
            // 重新更改对象中的key
            let arr = [] //新建一个数组
            for(let key in options){
                arr.push(options[key])
            }
            let newOptions = {} //新的对象 把数组转回对象 更新下标
            arr.forEach((item,index)=>{
                newOptions[index+1] = item
            })
            this.$set(item,'options',newOptions)

            // 还原正确答案
            item.answerArray = []
            answerArr.forEach(ans=>{
                // 获得下标 之前的正确答案在最新的答案列表里面的下标
                let index = arr.indexOf(ans);
                if(index != -1){
                    item.answerArray.push((index+1).toString())
                }
            })
            item.answerStringArray = item.answerArray.join(',') //还原正确答案
        },

        // 添加一个答案
        addAlist(item){
            // this.$set(item.options)
            let arr = Object.keys(item.options); 
            this.$set(item.options,arr.length+1,'')
        },

        // 添加题目 多个 接口
        async addQuestionList(){
            let examId = this.selectExam.id //当前选择的科目id
            let data = this.questionList //当前选择的科目的所有题目集合
            let result = await addQuestionListApi(examId,data)
            if(result.code==200){
                this.$message({type:'success',message:'保存成功'})
            }
        },
        
        // 点击保存按钮
        clickSave: debounce(async function(){
            // 判断能否保存
            if(!this.isSaveJudge()) return
            // 获取富文本的内容
            this.questionList.forEach((item,index)=>{
                let content = this.$refs.wangEditor[index].getEditorDataFn();
                item.tips = content
            })
            await this.addQuestionList() // 添加题目 多个
            this.getQuestionList() // 重新根据科目获取题目
        },500),

        // 判断能否保存
        isSaveJudge(){
            let isSave = true
            let question = this.questionList
            for (let i = 0; i < question.length; i++) {
                // 填写问题
                if(question[i].question == ''){
                    this.$message({type:'warning',message:'请填写问题'})
                    isSave = false
                    return
                }
                // 添加答案
                if(JSON.stringify(question[i].options) === '{}'){
                    this.$message({type:'warning',message:'请添加答案'})
                    isSave = false
                    return
                }
                // 填写答案
                for(let key in question[i].options){
                    if(question[i].options[key] == ''){
                        this.$message({type:'warning',message:'请填写答案'})
                        isSave = false
                        return
                    }
                }
                // 勾选正确答案
                if(question[i].answerStringArray == ''){
                    this.$message({type:'warning',message:'请勾选正确答案'})
                    isSave = false
                    return
                }
                // 填写答案解析
                if(question[i].analysis == ''){
                    this.$message({type:'warning',message:'请填写答案解析'})
                    isSave = false
                    return
                }
            }
            return isSave
        },

        // --------------------学习情况--------------------

        // 打开学习情况抽屉
        openCondition(){
            this.showDrawer = true
        },
    },
}
</script>

<style scoped lang="scss">
.question-Box{
    height: 100%;
    .el-row{
        height: 100%;
        .el-card{
            position: relative;
        }
    }
}

// 学习情况按钮
.handleBtn {
  color: #f87a23;
  font-size: 12px;
}

// 添加按钮
.addBox {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 999;
    .el-button {
        width: 100%;
        border: 0;
        border-top: 1px solid #ecedf0;
        background-color: #f8f8f8;
        line-height: 25px;
        color: #606e84;
    }
    .addForm{
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        border-top: 1px solid #ecedf0;
        background-color: #f8f8f8;
        padding: 10px 0;
        // 输入框
        .addForm-input{
            width: 66%;
        }
        // 按钮
        .addForm-btn{
            width: 24%;
        }

        .el-select,
        .el-input{
            width: 18%;
            margin-right: 5px;
        }
        .el-button{
            width: 49%;
            padding: 2px 0;
            background-color: #fff;
            border: 1px solid #ecedf0;
            margin-left: 2%;
        }
        .addBtn{
            background-color: #f87a23;
            border-color: #f87a23;
            color: #fff;
            margin-left: 0;
        }
    }
}

// 分页
.pagination{
    text-align: center;
    margin-top: 20px;
    margin-bottom: 60px;
}

// 折叠面板
.el-collapse{
    margin-bottom: 80px;
    // 答案列表
    ul{
        li{
            display: flex;
            align-items: center;
            padding: 5px 0;
            i{
                font-size: 14px;
                margin-right: 10px;
                cursor: pointer;
            }
            .el-input{
                margin-right: 10px;
            }
        }
    }
    // 添加答案按钮
    .addAnswer{
        font-size: 16px;
        color: #666;
        cursor: pointer;
    }
}

// 空状态
.analysis-empty{
    text-align: center;
    font-size: 14px;
    font-weight: 400;
    color: #9B9B9B;
    margin-top: 30px;
    img{
        width: 28%;
    }
}

// 提示
.inputTxt{
    margin: 10px 0;
    p{
        font-size: 14px;
        color: #2e3f5e;
    }
}
</style>

<style scoped>
ul,
h3,
h4,
p {
  margin: 0;
  padding: 0;
  list-style: none;
}
::v-deep .question-scoll .el-card__body{
    height: 100%;
}
::v-deep .question-scoll .el-card__body>div{
    height: calc(100% - 44px);
    overflow-y: auto;
}
::v-deep .question-scoll .el-card__body>div::-webkit-scrollbar{
    width: 0;
}

.quesScoll-box{
    height: 100%;
    overflow-y: auto;
}
.quesScoll-box::-webkit-scrollbar{
    width: 0;
}

.addForm >>> .el-input__inner{
    padding: 0 5px;
}

.inputTxt >>> .el-textarea__inner{
    font-family: Microsoft Yahei;
}

/* 表格样式 */
::v-deep .el-table::before{
    height: 0;
}
/* 表格输入框 */
::v-deep .tableInput .el-input__inner{
    border: 0;
    padding: 0;
}

::v-deep .el-table .el-table__header-wrapper th{
  background-color: #fff;
}
::v-deep .el-table th.is-leaf{
  border-top: 1px solid #EFEFEF;
  border-bottom: 1px solid #EFEFEF;
}
::v-deep .el-table th > .cell{
  font-size: 12px;
  color: #909AAA;
}
::v-deep .el-table .cell,
::v-deep .el-table .cell p{
  margin: 0;
  font-size: 14px;
  color: #2E3F5E;
}
::v-deep .el-table .cell .el-button{
  color: #F87A23;
}
::v-deep .el-table .cell .el-table__expand-icon i::before{
  content: "\E791";
}
::v-deep .el-table td{
  /* border-bottom: 0; */
}
::v-deep .el-table td .islight{
  color: #F87A23;
  cursor: pointer;
}
::v-deep .el-table .el-table__expanded-cell[class*=cell]{
  padding: 0;
}
::v-deep .el-table__expanded-cell .el-table::before{
  height: 0;
}
::v-deep .el-table__expanded-cell .el-table th.is-leaf{
  border-top: 0;
}
::v-deep .el-table__expanded-cell .el-table td{
  border-bottom: 0;
}
::v-deep .el-table__body tr.current-row > td{
    background-color: #f3f3f3;
}
/* 表格样式 end */

/* 折叠面板 */
::v-deep .el-collapse .el-collapse-item__header{
    height: 60px;
    line-height: 60px;
}
.el-collapse .coll-title {
    width: 90%;
    display: flex;
    align-items: center;
    font-size: 14px;
    font-weight: 600;
    color: #2e3f5e;
}
.el-collapse .coll-title i{
    margin-right: 5px;
}
.el-collapse .coll-title .el-input{
    width: calc(100% - 20px);
}
::v-deep .el-collapse .el-collapse-item__content {
    padding-left: 30px;
    padding-bottom: 0;
}
::v-deep .el-collapse .el-icon-arrow-right:before {
    content: "\E790";
}
::v-deep .el-collapse .el-collapse-item__arrow.is-active {
    transform: rotate(180deg);
}

/* 富文本 */
::v-deep .inputTxt .w-e-toolbar{
  z-index: 2000 !important;
}
::v-deep .inputTxt .w-e-text-container {
  height: 100px !important;
  z-index: 2000 !important;
}

/* 抽屉样式 */
::v-deep .el-drawer__header{
    border-bottom: 1px solid #EFEFEF;
    padding-bottom: 15px;
    margin-bottom: 20px;
}
::v-deep .el-drawer__header>span{
    font-size: 18px;
    font-weight: bold;
    color: #2E3F5E;
    padding-left: 20px;
    background: url('~@/wss/assets/image/icon/cardLeft.png') left center no-repeat;
    background-size: 7px;
}

/* 右侧按钮样式 */
::v-deep .subBtn {
  padding: 8px 30px;
  z-index: 2001;
}
::v-deep .subBtn .el-button {
  width: 100px;
  padding: 8px 0;
  font-size: 14px;
  color: #606e84;
}
::v-deep .subBtn .el-button--primary {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
}

</style>